import audioop
import base64
import os

import requests
def call_transfer_api(title:str, speech: bytes, from_user: str= None, to_user:str = None):
    url = "http://192.168.102.9:37090/open/asr/offline"
    headers = {
        "Authorization": "Access=18"
    }
    myParams = {"itn": True, "wav": base64.b64encode(speech), 'title': title, 'format': 'wav', 'speaker': True, 'punc': True, 'fromUser':from_user, 'toUser':to_user}
    res = requests.post(url=url,headers=headers, json=myParams)

    print("response:", res.text)  # 返回请求结果
def walk_wave_from_folder(parent_path: str, parent_title:str = ''):
    files = os.listdir(parent_path)
    for file in files:
        if file.startswith('.'):
            continue
        file_path = os.path.join('{0}/'.format(parent_path), file)
        if os.path.isdir(file_path):
            if parent_title:
                title = parent_title + '-' + file
            else:
                title = file
            walk_wave_from_folder(parent_path=file_path, parent_title=title)
        elif file_path.endswith('.wav'):

            with open(file_path, "rb") as f:
                wav_data = f.read()
                f.close()
                if parent_title:
                    title = parent_title + '-' + file.replace('.wav', '')
                else:
                    title = file.replace('.wav', '')
                #print(title)
                #print(f'title={title} from_user:{from_user} to_user:{to_user}')
                call_transfer_api(title=f'{title}', speech=wav_data)


def walk_wave_datas():

    root_path = '/home/leo/Documents/济南局/转写准确率样本/测试样本/调度录音'
    walk_wave_from_folder(parent_path=root_path)
    '''
    root_path = '/home/leo/Downloads'
    root_files = os.listdir(root_path)
    for file in root_files:
        if file.startswith('.'):
            continue

        file_path = os.path.join('{0}/'.format(root_path), file)
        if os.path.isdir(file_path):
            continue
        elif file_path.endswith('.wav'):
            print(file_path)
            with open(file_path, "rb") as f:
                wav_data = f.read()
                f.close()

                title = file.replace('.wav', '')
                names = title.split('_')
                from_user = ''
                to_user = ''
                if len(names) > 1:
                    from_user = names[1]
                if len(names) > 2:
                    to_user = names[2]
                # print(f'title={title} from_user:{from_user} to_user:{to_user}')
                call_transfer_api(title=f'{title}', speech=wav_data, from_user=from_user, to_user=to_user)
    '''


walk_wave_datas()